import { observable, computed, flow, makeObservable, action } from 'mobx'

class AppleStore {
    constructor() {
        makeObservable(this)//新版本需要添加此项以使视图能够更新
    }
    @observable apples = [];//储存所有苹果数据
    @observable appleId = 1;//苹果id标记，只会增加，不会减少
    @observable isPicking = false;//判断是否正在摘取
    /**
     * 摘取一个苹果的整个流程
     */
    applePick = flow(function* () {
        this.startPick()
        yield setTimeout(() => {
            this.pickApple()
            this.increaseId()
            this.stopPick()
        }, 1000);
    }).bind(this)
    /**
     * 摘取一个苹果
     */
    @action.bound pickApple(){
        this.apples.push({
            appleId: this.appleId,
            weight: parseInt((Math.random() * 200 + 200).toFixed(0)),
            isEated: false

        })
    }
    /**
     * 吃掉一个苹果
     * @param {int} appleId 
     */
    @action.bound appleEat(appleId) {
        let eatingApple = this.apples.find(apple =>apple.appleId === appleId)
        eatingApple.isEated = true;
    }
    /**
     * 开始摘苹果
     */
    @action.bound startPick(){
        this.isPicking=true;
    }
    /**
     * 停止摘苹果
     */
    @action.bound stopPick(){
        this.isPicking=false;
    }
    /**
     * 苹果id+1
     */
    @action.bound increaseId(){
        this.appleId++;
    }
    /**
     * 是否可摘苹果
     */
    @computed get pickable() {
        return !this.isPicking
    }
    /**
     * 现有苹果统计
     */
    @computed get storedApples() {
        return this.apples.filter(apple => apple.isEated === false);
    }
    /**
     * 已经吃过的苹果统计
     */
    @computed get eatedApples() {
        return this.apples.filter(apple => apple.isEated === true);
    }
}
const apple = new AppleStore()
export default apple